﻿/***************************************************
 *
 *功能：Wifi打卡
 *
 * 状态：启用
 * 创建时间：2018-07-20
 **************************************************/
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using com.nm.ApiServer;
using com.nm.ApiServer.Attributes;
using com.nm.Attributes;
using com.nm.db.Models.Ehr;
using com.nm.db.Models.Terminal;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Senparc.Weixin;
using Senparc.Weixin.Work.AdvancedAPIs;
using Senparc.Weixin.Work.Containers;
using WeiXinAPI.Common;

namespace WeiXinAPI
{
    public class WxPunchClockHandler:BaseHandler
    {
        /// <summary>
        /// 初始页面信息
        /// </summary>
        /// <param name="Code"></param>
        /// <param name="wxConfig"></param>
        /// <returns></returns>
        [Description("初始页面信息")]
        [ReturnType(typeof(PunchResult))]
        public ApiResult GetUserInfo([ParamDescription("Code")]string Code, [ParamDescription("应用记录ID")]string wxConfig)
        {

            try
            {
                var wxInfo = WXBaseHandler.TryGetWxCorpInfo(wxConfig);
                if (wxInfo.CorpInfo == null)
                {
                    return Error(wxInfo.Message);
                }
                var dc = new ehrEntities();
                var accessToken = AccessTokenContainer.TryGetToken(wxInfo.CorpInfo.CorpID, wxInfo.CorpInfo.CorpSercet);
                //同token和code获取当前用户Id
                var punchResult = new PunchResult();
                ////获取当天打卡数据
                //var aaa = dc.WxCheckin
                //    .Where(t => t.userid == "WenZhong" &&
                //                t.checkin_time == DbFunctions.TruncateTime(DateTime.Now))
                //    .Select(t => new PunchDetail()
                //    {
                //        userid = t.userid,
                //        checkin_time = t.checkin_time,
                //        wifiname = t.wifiname
                //    }).ToList();
               
                //punchResult.punchs = aaa;

                //return Success(punchResult);


                var user = OAuth2Api.GetUserId(accessToken, Code);
                if (user.errcode == ReturnCode_Work.请求成功)
                {
                    //获取用户详情
                    var result = MailListApi.GetMember(accessToken, user.UserId);
                    if (result.errcode == ReturnCode_Work.请求成功)
                    {
                        var userInfo = new UserInfo()
                        {
                            UserId = result.userid,UserName = result.name
                        };
                        var beginTime =Convert.ToDateTime(DateTime.Now.ToShortDateString() + " 00:00:00");
                        var endTime = Convert.ToDateTime(DateTime.Now.ToShortDateString() + " 23:59:59");
                        //获取当天打卡数据
                        var punch = dc.KM_EHR_WECHAT_CARD
                            .Where(t => t.userid == result.userid &&
                                        t.checkin_time >=beginTime && t.checkin_time<=endTime)
                            .OrderBy(t=>t.checkin_time)
                            .Select(t => new PunchDetail()
                            {
                                userid = t.userid,
                                checkin_time = t.checkin_time,
                                wifiname = t.wifiname
                            }).ToList();
                        punchResult.users = userInfo;
                        punchResult.punchs = punch;
                        punchResult.netWorkTime = GetNetDateTime();
                    }
                }
                return Success(punchResult);


            }
            catch (Exception ex)
            {
                return Error(ex.Message);
            }
        }

        DateTime GetNetWorkTime()
        {
            var http = new HttpHelper();
            var item = new HttpItem()
            {
                URL = "http://www.hko.gov.hk/cgi-bin/gts/time5a.pr?a=1",
                Method = "GET",
            };
            var R = http.GetHtml(item);
            var regex = new Regex(@"0=(?<timestamp>\d{10})\d+");
            var match = regex.Match(R.Html);
            return match.Success ? GetTime(match.Groups["timestamp"].Value) : DateTime.Now;
        }

        /// <summary>
        /// 获取网络日期时间  
        /// </summary>  
        /// <returns></returns>  
        public DateTime GetNetDateTime()
        {
            WebRequest request = null;
            WebResponse response = null;
            WebHeaderCollection headerCollection = null;
            string datetime = string.Empty;
            try
            {
                request = WebRequest.Create("https://www.baidu.com");
                request.Timeout = 3000;
                request.Credentials = CredentialCache.DefaultCredentials;
                response = (WebResponse)request.GetResponse();
                headerCollection = response.Headers;
                foreach (var h in headerCollection.AllKeys)
                { if (h == "Date") { datetime = headerCollection[h]; } }
                return Convert.ToDateTime(datetime);
            }
            catch (Exception) { return DateTime.Now; }
            finally
            {
                if (request != null)
                { request.Abort(); }
                if (response != null)
                { response.Close(); }
                if (headerCollection != null)
                { headerCollection.Clear(); }
            }
        }

        /// <summary>
        /// 时间戳转为C#格式时间
        /// </summary>
        /// <param name=”timeStamp”></param>
        /// <returns></returns>
        private DateTime GetTime(string timeStamp)
        {
            DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            long lTime = long.Parse(timeStamp + "0000000");
            TimeSpan toNow = new TimeSpan(lTime); return dtStart.Add(toNow);
        }

        /// <summary>
        /// 日期转换成unix时间戳
        /// </summary>
        /// <param name="dateTime"></param>
        /// <returns></returns>
        public static long DateTimeToUnixTimestamp(DateTime dateTime)
        {
            DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)); // 当地时区
            long timeStamp = (long)(dateTime - startTime).TotalMilliseconds; // 相差毫秒数
            return timeStamp;
        }

        /// <summary>
        /// 打卡
        /// </summary>
        /// <param name="detail"></param>
        /// <returns></returns>
        [JsonType]
        [Description("保存打卡数据")]
        [ReturnType(typeof(int), "0-成功")]
        public ApiResult PunchCheck([ParamDescription("打卡对象")]KM_EHR_WECHAT_CARD detail)
        {
            try
            {
                var ehr = new ehrEntities();
                if(string.IsNullOrWhiteSpace(detail.userid))return Error("员工号为空!");
                var timeStamp = DateTimeToUnixTimestamp(Convert.ToDateTime(detail.checkin_time));
                var checkType = string.IsNullOrWhiteSpace(detail.checkin_type)? "微信打卡":detail.checkin_type;
                var exceptionType = string.IsNullOrWhiteSpace(detail.exception_type) ? "正常打卡" : detail.exception_type;
                var query = ehr.Database.ExecuteSqlCommand($@"exec KM_EHR_INSERT_INTO_WECHAT_CARD '{detail.userid}','{checkType}','{exceptionType}','{timeStamp}','{detail.wifiname}','{detail.notes}','{detail.wifimac}'");
            }
            catch (Exception ex)
            {
                return Error(ex.Message);
            }
            return Success(0);
        }


    }

    public class PunchResult
    {
        public UserInfo users { get; set; }

        public IList<PunchDetail> punchs { get; set; }

        public DateTime netWorkTime { get; set; }
    }

    /// <summary>
    /// 企业员工信息
    /// </summary>
    public class UserInfo
    {
        public string UserId { get; set; }

        public string UserName { get; set; }
    }

    public class PunchDetail
    {
        public string userid { get; set; }
        public DateTime? checkin_time { get; set; }
        public string wifiname { get; set; }
    }
}
